package com.benson.common.cron.config;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import com.benson.common.cron.annotation.CronConfig;
import com.benson.common.cron.entity.CronCommonConfig;
import com.benson.common.cron.util.QuartzUtils;
import org.quartz.Job;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 定时任务 初始化
 *
 * @author zhangby
 * @date 24/2/20 1:37 pm
 */
@Component
public class CronInitServer implements CommandLineRunner {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    CronCommonConfig cronCommonConfig;

    @Autowired
    Scheduler scheduler;

    /**
     * 初始化
     */
    @Override
    public void run(String... args) throws Exception {
        Set<Class<?>> classes = ClassUtil.scanPackage(cronCommonConfig.getScanPackage());
        List<Class<?>> classList = classes.stream()
                .filter(clazz -> ObjectUtil.isNotNull(clazz.getAnnotation(CronConfig.class)))
                .collect(Collectors.toList());
        logger.info("加载定时任务： ");
        classList.forEach(clazz -> {
            QuartzUtils.createScheduleJob(scheduler, (Class<? extends Job>) clazz);
        });
        logger.info("定时任务加载成功");
    }
}
